import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from 'antd';
import AntdForm from '@/components/AntdForm';
import StandardTable from '@/components/StandardTable';
import AdButton from '@/components/AdButton';
import AntdInput from '@/components/AntdInput';
import { queryDict } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import {
  allDispatchType,
  selectBillDetailAndInfo,
  renderTableAdSelect,
  codes,
  getBillVehicleIDetails,
  getBillOilDetails,
} from './utils';
import styles from './Bill.less';

@connect(({ vehicle, component, loading }) => ({
  borrowInfo: vehicle.borrowInfo,
  billDetail: vehicle.billDetail,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.addInfo],
}))
@Form.create()
export default class BorrowInfo extends Component {
  state = { id: '', borrowData: {} };

  componentWillMount() {
    const allDict = [allDictList.currencyType];
    queryDict({ props: this.props, allDict });
  }
  componentDidMount() {
    const { detailId, type, billDetail, onRef, open } = this.props;
    const details = billDetail[detailId] || {};
    const id = open ? details.id : detailId;
    if (details) {
      const { realCurrencyType, relationObjId, payCompany, receiverType } = details;
      const params = {
        currency: realCurrencyType,
        loanPerson: relationObjId,
        payCompanyId: payCompany,
        receiverType,
        id,
      };
      this.selectBorrowDetail(params);
    }

    this.handleStateChange([{ id }]);

    onRef && onRef(this);
  }
  componentWillReceiveProps(nextProps, nextState) {
    const { detailId, billDetail, open } = nextProps;

    if (
      JSON.stringify(billDetail) !== JSON.stringify(this.props.billDetail) ||
      this.props.detailId !== detailId
    ) {
      const details = billDetail[detailId] || {};
      const id = open ? details.id : detailId;
      let params = {
        currency: details ? details.realCurrencyType : '',
        loanPerson: details ? details.relationObjId : '',
        payCompanyId: details ? details.payCompany : '',
        receiverType: details ? details.receiverType : '',
        id,
      };
      if (id && details) {
        this.handleStateChange([{ id }]);
        if (params.currency) this.selectBorrowDetail(params);
      }
    }
  }
  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };
  selectBorrowDetail = params => {
    const { currency, loanPerson, payCompanyId, receiverType } = params;
    const { open } = this.props;
    params.open = open;
    if (currency && loanPerson && payCompanyId && receiverType) {
      selectBillDetailAndInfo({
        type: allDispatchType.borrowInfo,
        payload: params,
        props: this.props,
        callback: data => {
          const { billDetail, detailId, mode } = this.props;
          const detail = billDetail[detailId];

          if (detail && detail.rushedJson) {
            let rushed = JSON.parse(detail.rushedJson);
            rushed = rushed.rushedListVOS;
            if (mode === 'detail') {
              this.setState({
                borrowData: { list: rushed },
              });
            } else {
              data.list &&
                data.list.map(v => {
                  rushed.map(r => {
                    if (v.loanNo == r.loanNo && r.offsetAmount) {
                      v.offsetAmount = r.offsetAmount;
                    }
                  });
                });
              this.setState({
                borrowData: { list: data },
              });
            }
          } else {
            this.setState({
              borrowData: { list: [] },
            });
          }
        },
      });
    }
  };

  columns = [
    {
      title: '借款单号',
      dataIndex: 'loanNo',
      width: 120,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '借款日期',
      dataIndex: 'loanDate',
      width: 120,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '借款用途',
      dataIndex: 'loanPurpose',
      width: 120,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '币种',
      dataIndex: 'currency',
      width: 100,
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.currencyType,
        }),
    },
    {
      title: '借款原币金额',
      dataIndex: 'loanAmount',
      width: 120,
      render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
    },
    {
      title: '原币余额',
      dataIndex: 'loanBalance',
      width: 120,
      render: text => <span>{text && text !== 0 ? Number(text).toFixed(2) : 0}</span>,
    },
    {
      title: '冲抵金额',
      dataIndex: 'offsetAmount',
      width: 150,
      render: (text, record) => {
        const _text = text && text !== 0 ? Number(text).toFixed(2) : 0;
        if (this.props.mode === 'detail') {
          return <span>{_text}</span>;
        } else {
          return (
            <AntdInput
              value={text}
              onChange={value => this.handleFieldChange(value, 'offsetAmount', record)}
              disabled={this.props.status}
              mode="money"
            />
          );
        }
      },
    },
  ];

  calMoney = (inputVal, val, type) => {
    if (inputVal > val) {
    }
  };

  handleFieldChange(value, fieldName, record) {
    const { dispatch, billDetail, detailId } = this.props;

    const newData = this.getInfoData();
    const target = this.getRowByKey(record.loanNo, newData);

    if (target) {
      target[fieldName] = value;
    }
    this.saveAllValue({ borrowInfo: { list: newData } });
  }

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };
  getInfoData = () => {
    const { borrowInfo } = this.props;
    const { id } = this.state;
    let newData = [];
    const _borrowInfo = borrowInfo[id] || borrowInfo;
    if (_borrowInfo) {
      const data = _borrowInfo.list;
      newData = data.map(item => ({ ...item }));
    }
    return newData;
  };
  getRowByKey(loanNo, newData) {
    const data = this.getInfoData();
    return (newData || data).filter(item => item.loanNo === loanNo)[0];
  }

  render() {
    const { borrowInfo, form, loading, onSelectRow, mode, status, dictObject } = this.props;
    const { id, borrowData } = this.state;
    const data = mode === 'detail' ? borrowData : borrowInfo[id] || borrowInfo;
    return (
      <div className={styles.customPartsOfferInfo}>
        <AntdForm>
          <StandardTable
            disabledRowSelected={true}
            loading={loading}
            data={data}
            columns={this.columns}
            scrollY={200}
            scrollX={950}
            // code="BillInfo"
            pagination={false}
          />
        </AntdForm>
      </div>
    );
  }
}
